import { Component, Injector, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import {
    OperationHistoryServiceProxy, ProductionAssignmentServiceProxy,
    OperationLogDto, ProductionAssignmentInput, AssignmentOptionInput, CommonServiceProxy,
    MakeTaskServiceProxy
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { AppComponentBase } from '@shared/common/app-component-base';


@Component({
    selector: 'app-production-preparation',
    templateUrl: './production-preparation.component.html',
    styleUrls: ['./production-preparation.component.less']
})
export class ProductionPreparationComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    modelList: any[];
    lotNoList: any[];
    addInfo = new ProductionAssignmentInput();
    unitList: any[];
    actived = false;
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _productionAssignmentServiceProxy: ProductionAssignmentServiceProxy,
        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _commonServiceProxy: CommonServiceProxy,
        private _makeTaskServiceProxy: MakeTaskServiceProxy,
    ) {
        super(injector);
    }
    queryInfo = {
        id: undefined,//id
        model: undefined,//规格型号
        lotNo: undefined,//发次
        jobNumber: undefined,//任务编号
    };//查询条件
    selectedTable: any;//table 数据
    dialogType: string = '新增'
    addVisible: boolean = false;//弹窗 参数
    llVisible: boolean = false;//履历 参数
    introduceVisible: boolean = false;//生产准备任务引入 参数
    addInfoUi: any = {
        id!: "",
        planNumber!: "",
        model!: "",
        lotNo!: "",
        drawingNo!: "",
        jobNumber!: "",
        completionDate!: "",
        productName!: "",
        preparationRemark!: "",
        organizationUnitId!: "",
        organizationUnitDesc!: "",
        userId!: "",
        userName!: "",
        assignmentAuthor!: "",
        assignmentTime!: "",
        startTime!: "",
        endTime!: "",
        assignmentTypes!: undefined,
        assignmentTypesDesc!: "",
        remark!: "",
    };//新增集合
    userList: any[];//负责人 提报人下拉
    savingAddDia: boolean = false;//禁止频繁保存操作
    logList: OperationLogDto[];
    saveFlag = true;
    getDringNo(event) {
        this._makeTaskServiceProxy.getJobNumber(
            this.addInfoUi.lotNo.value,
            this.addInfoUi.model.value
        )
            .pipe(finalize(() => { })).subscribe(result => {
                this.addInfoUi.drawingNo = result.drawingNo;
                this.addInfoUi.productName = result.productName;
                this.addInfoUi.jobNumber = result.jobNumber;
            })
    }
    ngOnInit() {
        this.getUnitList()
        this.getmodelList()
    }
    //弹窗隐藏
    displayclose(): void {
        this.actived = false;
        this.addInfoUi = {
            id!: "",
            planNumber!: "",
            model!: "",
            lotNo!: "",
            drawingNo!: "",
            jobNumber!: "",
            completionDate!: "",
            productName!: "",
            preparationRemark!: "",
            organizationUnitId!: "",
            organizationUnitDesc!: "",
            userId!: "",
            userName!: "",
            assignmentAuthor!: "",
            assignmentTime!: "",
            startTime!: "",
            endTime!: "",
            assignmentTypes!: undefined,
            assignmentTypesDesc!: "",
            remark!: "",

        };//新增集合
    }
    //查看
    seeDetail(item) {
        this.actived = true;
        this.dialogType = '生产准备计划查看';
        this.setAddInfoUi(item)
    }
    //修改
    editDetail(item) {
        this.dialogType = '生产准备计划修改';
        this.setAddInfoUi(item)
    }
    //回显数据处理
    setAddInfoUi(item) {
        this.addInfoUi = JSON.parse(JSON.stringify(item))
        this.addVisible = true;
        let modelArr = this.modelList.filter((ele, index) => {
            return ele.value == item.modelId
        })
        this.addInfoUi.model = modelArr[0]
        this._commonServiceProxy.getLotNoList(
            this.addInfoUi.model.value
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.lotNoList = result
                let lonoArr = this.lotNoList.filter((ele, index) => {
                    return ele.value == item.lotNoId
                })
                this.addInfoUi.lotNo = lonoArr[0]
            });
        this.addInfoUi.organizationUnitId = []
        let organizationUnitIdArr = item.organizationUnitId.split(',')
        organizationUnitIdArr = organizationUnitIdArr.filter(num => num != '')
        organizationUnitIdArr.forEach(element => {
            this.addInfoUi.organizationUnitId.push(this.unitList.filter((ele, index) => {
                return ele.id == element
            })[0])
        });
        this.addInfoUi.userId = []
        const getuserList = new Promise(
            (resolve, reject) => {
                this._productionAssignmentServiceProxy.getOrganizationUnitUsersById(organizationUnitIdArr)
                    .pipe(finalize(() => { }))
                    .subscribe(result => {
                        this.userList = result
                        resolve(result)
                    });


            }
        )
        getuserList.then((list) => {
            let userIdArr = item.userId.split(',')
            userIdArr = userIdArr.filter(num => num != '')
            userIdArr.forEach(element => {
                this.addInfoUi.userId.push(this.userList.filter((ele, index) => {
                    return ele.id == element
                })[0])
            });
            this.actived = true;

        })



        // const getmodelList = new Promise(
        //   (resolve, reject) => {
        //     this._commonServiceProxy.getLotNoList()
        //       .pipe(finalize(() => { }))
        //       .subscribe(result => {
        //         // let arr = []
        //         // result.forEach(element => {
        //         //   arr.push(this.setSelectProps(element))
        //         // });
        //         // this.lotNoList = arr
        //         this.lotNoList = result

        //         resolve(this.lotNoList)

        //       });


        //   }
        // )
        // getmodelList.then((list) => {
        //   let lotNoArr = this.lotNoList.filter((ele, index) => {
        //     return ele.value == item.lotNo
        //   })
        //   this.addInfoUi.lotNo = lotNoArr[0]

        // })
        this.addInfoUi.completionDate = item.completionDate._d

    }
    // 新增
    addStandardDesc(): void {
        this.savingAddDia = true
        let organizationUnitIdArr = ""
        let organizationUnitDescStr = ""
        this.addInfoUi.organizationUnitId.forEach(element => {
            organizationUnitIdArr += `${element.id},`
            organizationUnitDescStr += `${element.displayName},`
        });
        let userIdStr = ""
        let userNameStr = ""
        this.addInfoUi.userId.forEach(element => {
            userIdStr += `${element.id},`
            userNameStr += `${element.userName},`
        });
        this.addInfo.organizationUnitId = organizationUnitIdArr
        this.addInfo.organizationUnitDesc = organizationUnitDescStr
        this.addInfo.userId = userIdStr
        this.addInfo.userName = userNameStr
        this.addInfo.preparationRemark = this.addInfoUi.preparationRemark
        this.addInfo.drawingNo = this.addInfoUi.drawingNo
        this.addInfo.completionDate = this.addInfoUi.completionDate
        this.addInfo.jobNumber = this.addInfoUi.jobNumber
        this.addInfo.lotNo = this.addInfoUi.lotNo.label
        this.addInfo.model = this.addInfoUi.model.label
        this.addInfo.lotNoId = this.addInfoUi.lotNo.value
        this.addInfo.modelId = this.addInfoUi.model.value
        this.addInfo.productName = this.addInfoUi.productName
        this.addInfo.remark = this.addInfoUi.remark
        this.addInfo.id = this.addInfoUi.id
        if (this.saveFlag) {
            this.saveFlag = false;
            this._productionAssignmentServiceProxy.insertOrUpdateProductionAssignment(
                this.addInfo
            )
                .pipe(finalize(() => { this.savingAddDia = false }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.addVisible = false
                        this._messageService.success('添加成功');
                        this.getDescList()
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    //启动 完成 删除
    optionAssignment(type, msg) {
        if (!this.selectedTable) {
            this._messageService.warn("请先选择一条数据")
            return
        }
        this._messageService.confirm(
            msg,
            (isConfirmed) => {
                if (isConfirmed) {
                    let assignmentsId = []
                    this.selectedTable.forEach(element => {
                        assignmentsId.push(element.id)
                    });
                    let obj = new AssignmentOptionInput()
                    obj.assignmentsId = assignmentsId
                    obj.option = type
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._productionAssignmentServiceProxy.optionAssignment(
                            obj
                        )
                            .pipe(finalize(() => { this.savingAddDia = false }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    if (type == 1) {
                                        this._messageService.success(' XXXX（任务编号）型号任务已启动，可进行生产作业！');

                                    } if (type == 0) {
                                        this._messageService.success('删除成功')
                                    } else {
                                        this._messageService.success('已完成')
                                    }
                                    this.selectedTable = [];
                                    this.getDescList()
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            }
        );
    }
    // 引入提交
    introducePlanEv(): void {
        this._messageService.confirm(
            '确定引用该条数据？',
            (isConfirmed) => {
                if (isConfirmed) {
                    this.savingAddDia = true
                    this.addInfo.jobNumber = this.addInfoUi.jobNumber
                    this.addInfo.lotNoId = this.addInfoUi.lotNo.value
                    this.addInfo.modelId = this.addInfoUi.model.value
                    this.addInfo.lotNo = this.addInfoUi.lotNo.label
                    this.addInfo.model = this.addInfoUi.model.label
                    this.addInfo.productName = this.addInfoUi.productName
                    this.addInfo.drawingNo = this.addInfoUi.drawingNo
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._productionAssignmentServiceProxy.introducePlan(
                            this.addInfo
                        )
                            .pipe(finalize(() => { this.savingAddDia = false }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.introduceVisible = false
                                    this._messageService.success('引用成功');
                                    this.getDescList()
                                } else {
                                    this._messageService.error(result.message)
                                }
                            });
                    }
                }
            }
        );

    }
    // 型号选择改变事件
    modelChangeEv(ev) {
        this.addInfoUi.jobNumber = this.addInfoUi.model.label + '/'
        this._commonServiceProxy.getLotNoList(ev.value)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.lotNoList = result
            });
    }
    //型号下拉
    getmodelList() {
        this._commonServiceProxy.getModelList(
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.modelList = result
            });
    }
    /**
     * 发次
      lotstr — (optional)
     model — (optional)
     */
    getLotNoList(event): any {
        this._commonServiceProxy.getLotNoList(
            this.addInfoUi.model.value
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.lotNoList = result
            });
    }
    // 组合为需要的数据格式
    setSelectProps(val) {
        return {
            label: val,
            value: val
        }
    }
    //引入
    introduceEv() {
        if (!this.selectedTable) {
            this._messageService.warn("请先选择一条数据")
            return
        }
        this.introduceVisible = true
        this.addInfoUi.jobNumber = this.selectedTable[0].jobNumber

    }
    //重置
    reset() {
        this.queryInfo = {
            id: undefined,//id
            model: undefined,//规格型号
            lotNo: undefined,//发次
            jobNumber: undefined,//任务编号
        }
        this.selectedTable = [];
    }
    //火箭生产准备计划列表
    getDescList(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this._productionAssignmentServiceProxy.getAssignments(
            this.queryInfo.id,
            this.queryInfo.model ? this.queryInfo.model.label : undefined,
            this.queryInfo.lotNo ? this.queryInfo.lotNo.label : undefined,
            this.queryInfo.model ? this.queryInfo.model.value : undefined,
            this.queryInfo.lotNo ? this.queryInfo.lotNo.value : undefined,
            this.queryInfo.jobNumber,
            this.primengTableHelper.getSorting(this.dataTable),//undefined
            this.primengTableHelper.getMaxResultCount(this.paginator, event),//10
            this.primengTableHelper.getSkipCount(this.paginator, event)//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();

            });
    }
    /**
       * 负责人  
       */
    getUserList(idArr): void {
        this._productionAssignmentServiceProxy.getOrganizationUnitUsersById(idArr)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.userList = result
            });
    }
    //班组 change事件
    unitChangeEv(ev) {
        this.addInfoUi.userId = [];
        let idArr = []
        ev.forEach(element => {
            idArr.push(element.id)
        });
        this.getUserList(idArr)
    }
    //履历
    llVisibleEv(id) {
        this.llVisible = true
        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result

            });
    }
    //负责班组
    getUnitList(): void {
        this._productionAssignmentServiceProxy.getOrganizationUnit()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.unitList = result
            });
    }
}
